from re import T, U
import os

from django.shortcuts import render
from django.core.management import call_command
from rest_framework import response, generics, status
from .serializers import RegistrationSerializer,UserSerializer
from .models import Role, Tenant, User
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError
from rest_framework import generics, response, status, viewsets


class LoginView(TokenObtainPairView):

    def post(self, request, *args, **kwargs):
        email, password = request.data.get('email'), request.data.get('password')

        serializer = self.get_serializer(data={
            'username': User.get_default_username(email),
            'password': password
        })

        try:
            serializer.is_valid(raise_exception=True)
        except TokenError as e:
            raise InvalidToken(e.args[0])

        instance = serializer.user
        user_data = UserSerializer(instance).data
        tokens = serializer.validated_data

        return response.Response({
            'tokens': tokens,
            'user': user_data
        }, status=status.HTTP_200_OK)


class UserViewSet(viewsets.ModelViewSet):

    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_object(self):
        """
        Depends on whether a specifci lookup PK is given, will
        retrieve the current user's or the corresponding user's instance.
        """
        if not self.kwargs:
            user_id = self.request.user.id
            filter_kwargs = {self.lookup_field: user_id}
        else:
            filter_kwargs = {self.lookup_field: self.kwargs[self.lookup_field]}

        queryset = self.filter_queryset(self.get_queryset())
        instance = generics.get_object_or_404(queryset, **filter_kwargs)

        # May raise a permission denied
        self.check_object_permissions(self.request, instance)

        return instance

    def list(self, request, *args, **kwargs):
        user_id = self.request.user.id
        instance = User.objects.get(id=user_id)
        data = UserSerializer(instance).data
        return response.Response(data, status=status.HTTP_200_OK)

# Create your views here.
def issue_token_for(user):
    refresh_token=RefreshToken.for_user(user)
    access_token=refresh_token.access_token
    return {
        'refresh':str(refresh_token),
        'access':str(access_token)
    }

class RegisterView(generics.GenericAPIView):
    permission_classes=()
    serializer_class=RegistrationSerializer
    def post(self,request):
        data = request.data
        serializer=self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)

        schema_name=User.get_default_schema(data['email'])
        tenant=Tenant.objects.create(schema_name=schema_name)
        default_role=os.environ['DJANGO_DEFAULT_USER_ROLE']
        if default_role=='admin':
            user_role=Role.objects.create_admin_role(tenant)
        elif default_role =='basic':
            user_role=Role.objects.create_basic_role(tenant)
        else:
            return response.Response('',status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        call_command('tenant_migrate')
        user=User.objects.create(
            email=request.data['email'],
            password=request.data['password'],
            first_name=request.data['first_name'],
            last_name=request.data['last_name'],
            tenant=tenant,
            roles=[user_role],

        )
        user_token=issue_token_for(user)
        serializer=UserSerializer(user)
        return response.Response({
            'access':user_token['access'],
            'user':serializer.data
        })
